package com.star.ms.generation.utils;

import com.star.ms.common.pojo.product.Product;
import com.star.ms.common.utils.JsonUtil;
import com.star.ms.generation.dto.ProductDto;
import com.star.ms.generation.dto.ReviewsDto;

import java.io.IOException;
import java.util.*;

public class GeneratorUtil {
    public static List<ProductDto> getProductFromJson(String ...jsonFileName){
        List<ProductDto> list = new LinkedList<>();
        try {
            for (String fileName : jsonFileName) {
                list.addAll(JsonUtil.load(fileName).toJavaList(ProductDto.class));
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return list;
    }

    /**
     * 从 JSON 数据文件中读取商品信息
     * @param jsonFileName
     * @return
     */
    public static List<Product> getProductFromJsonFormat(String ...jsonFileName){
        Set<Product> set = new HashSet<>();
        for (String fileName : jsonFileName) {
            for (ProductDto p : getProductFromJson(fileName)) {
                Product product = new Product();
                product.setName(p.getProduct_name());
                product.setPrice(p.getProduct_price());
                product.setImg(p.getReview_product_img());
                product.setDetail(p.getProduct_detail());
                System.out.println("detail:" + p.getProduct_detail());
                set.add(product);
            }
        }
        return new ArrayList<>(set);
    }

    public static List<ReviewsDto> getReviewsFromJson(String ...jsonFileName){
        List<ReviewsDto> list = new LinkedList<>();
        try {
            for (String fileName : jsonFileName) {
                list.addAll(JsonUtil.load(fileName).toJavaList(ReviewsDto.class));
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return list;
    }

    // 受顺序的影响
    public static List<Review> getReviewsFromJsonFormat(String ...jsonFileName){
        Set<Review> set = new HashSet<>();
        List<ReviewsDto> list = getReviewsFromJson(jsonFileName);
        long reviewId = 1;  // 评论信息的ID
        long productId = 1; // 商品的ID
        Map<String, Long> map = new HashMap<>(); // 记录商品名称到商品ID的映射
        // 使用 Map对评价数据进行处理
        for (ReviewsDto origin : list) {
            Review review = new Review();
            review.setReviewsId(reviewId);
            review.setReviewsOrderId(reviewId++);   // 订单ID暂时和评论ID一致
            // 设置商品ID
            if(!map.containsKey(origin.getProduct_name())){
                map.put(origin.getProduct_name(), productId++);
            }
            review.setReviewsProductId(map.get(origin.getProduct_name()));
            review.setReviewsInfo(origin.getReviews_info());
            review.setReviewsTime(origin.getReviews_time());
            review.setReviewsRank(origin.getReviews_rank());
            set.add(review);
        }
        return new ArrayList<>(set);
    }
}
